<?php

class App_Methods_Request_SaveUserPulpitVisibilities {

  /**
   *
   * @var App_Methods_Data_App
   */
  public $app;
  public $applicationIds;

  public function __construct($params) {
    $this->app = new App_Methods_Data_App($params->app);
    $this->applicationIds = ($params->getDefault('applicationIds') == null) ? array() : $params->getDefault('applicationIds');
  }

  public function process() {
    $applications = ApplicationsQuery::create()
    ->leftJoinUserPulpit()
    ->addJoinCondition('UserPulpit', 'UserPulpit.UserId = ?', Core_Auth::getInstance()->getUser()->getId())
    ->with('UserPulpit')
    ->find();
    
    $visibleApplicationIds = array();
    $hiddenApplicationIds = array();
    $con = Propel::getConnection();
    $con->beginTransaction();
    try {
	    foreach ($applications as $application) {
	    	if (!$application->getUserPulpits()->getFirst() instanceof UserPulpit) {
	    		$userPulpit = new UserPulpit();
	    		$userPulpit->setDefaultData();
	    		$userPulpit->setVisible((in_array($application->getId(), $this->applicationIds)) ? 1 : 0);
	    		$applications->addUserPulpit($userPulpit);
	    	}
	    	else {
	    		$userPulpit = $application->getUserPulpits()->getFirst();
	    		$userPulpit->setVisible((in_array($application->getId(), $this->applicationIds)) ? 1 : 0);
	    	}
	    	if ($userPulpit->getVisible() == 1)
	    		$visibleApplicationIds[] = $application->getId();
	    	else
	    		$hiddenApplicationIds[] = $application->getId();
	    }
	    $applications->save($con);
	    $con->commit();
    } catch (Exception $e) {
    	$con->rollBack();
    	throw $e;
    }
    
    return new App_Methods_Response_SaveUserPulpitVisibilities(true, $visibleApplicationIds, $hiddenApplicationIds);
  }

}